package com.alibaba.sdk.config.shiro;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.constant.ApplicationErrorConstant;
import com.alibaba.sdk.constant.UserInfoConstant;
import com.alibaba.sdk.model.OperationResult;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * shiro登录过滤器
 *
 * @ writer Shawn(Shawn_0217@163.com)
 * @ date & time 2021/4/27 0:50
 * @ company alibaba
 */
public class ShiroLoginFilter extends FormAuthenticationFilter {

    /**
     * 如果isAccessAllowed返回false,则执行onAccessDenied
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);

        // "记住我"状态下，但是用户的session已经超时。即isRemembered为true、isAuthenticated为false
        if (!subject.isAuthenticated() && subject.isRemembered()) {
            if (subject.getSession().getAttribute(UserInfoConstant.USER) == null && subject.getPrincipal() != null) {
                // 重新设定cookie
                subject.getSession().setAttribute(UserInfoConstant.USER, subject.getPrincipal());
            }
        }
        return subject.isAuthenticated() || subject.isRemembered();
    }

    /**
     * 用户未登录处理
     *
     * @param request
     * @param response
     * @return false, 不继续执行其他过滤器
     * @throws IOException
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        setResponse(request, response, OperationResult.failWithCode(ApplicationErrorConstant.USER_NO_LOGIN));
        return false;
    }

    /**
     * 设置response的header信息
     *
     * @param response
     */
    private void setResponse(ServletRequest request, ServletResponse response, Object returnObj) throws IOException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");

        // 如果不设置的接受的访问源，前端都会报跨域错误，因为这里还没到corsConfig里面
        httpServletResponse.setHeader("Access-Control-Allow-Origin", ((HttpServletRequest) request).getHeader("Origin"));
        httpServletResponse.getWriter().write(String.valueOf(JSON.toJSON(returnObj)));
    }
}